package com.example.java_chatroom.Controller;

import com.example.java_chatroom.model.*;
import com.example.java_chatroom.service.GroupChatService;
import com.example.java_chatroom.service.MessageService;
import com.example.java_chatroom.service.MessageSessionService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Slf4j
@RequestMapping("/messageSession")
@RestController
public class MessageSessionController {
    @Autowired
    private MessageSessionService messageSessionService;

    @Autowired
    private GroupChatService groupChatService;

    @Autowired
    private MessageService messageService;
    ObjectMapper objectMapper = new ObjectMapper();

    @RequestMapping("/quitFriend")
    public Result quitFriend(Integer sessionId, Integer friendId) {
        messageService.deleteMessageUser(sessionId, friendId);
        return Result.success("退出群聊");
    }
    @RequestMapping("/insertFriends")
    public Result insertFriends(Integer sessionId, String friends) {
        List<FriendInfo> friendInfos = null;
        try {
            friendInfos = objectMapper.readValue(friends, new TypeReference<List<FriendInfo>>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        for (FriendInfo friendInfo : friendInfos) {
            messageSessionService.insertMessageSessionUser(sessionId, friendInfo.getFriendId());
        }
        return Result.success(1);
    }

    @RequestMapping("/deleteSession")
    public Result deleteSession(Integer sessionId) {
        messageSessionService.deleteSession(sessionId);
        messageSessionService.deleteSessionUser(sessionId);
        messageService.deleteMessage(sessionId);
        groupChatService.deleteChat(sessionId);
        return Result.success("删除成功");
    }

    @RequestMapping("/InviteFriends")
    public Result InviteFriends(Integer sessionId, String friends, String groupTitle,String userId) {

        List<FriendInfo> friendInfos = null;
        try {
            friendInfos = objectMapper.readValue(friends, new TypeReference<List<FriendInfo>>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        for (FriendInfo friendInfo : friendInfos) {
            messageSessionService.insertMessageSessionUser(sessionId, friendInfo.getFriendId());
        }
        messageSessionService.insertGroupTitle(sessionId, groupTitle, userId);
        return Result.success(groupTitle);
    }
    @RequestMapping("/getSessionId")
    public Result getSessionId() {
        SessionPersonage sessionPersonage = new SessionPersonage();
        messageService.insertSession(sessionPersonage);
        return Result.success(sessionPersonage.getSessionId());

    }
    @RequestMapping("/sessionList")
    public Result getMessageSessionList(HttpServletRequest request) {
        List<MessageSession> messageSessionList = new ArrayList<>();
        //获取当前用户的UserId
        HttpSession session = request.getSession(false);
        if (session == null) {
            System.out.println("[getMessageSessionList] 当前获取不到 Session 对象！");
            return Result.fail("用户未登陆");
        }
        UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
        if (userInfo == null) {
            System.out.println("没有找到UserInfo对象");
            return Result.fail("用户未登陆");
        }
        //根据userId查找数据库，查出来一哪些sessionId
       List<Integer> sessionIds = messageSessionService.getMessageIdsByUserId(userInfo.getUserId());
        for (Integer sessionId : sessionIds) {
            MessageSession messageSession = new MessageSession();
            // 遍历sessionId，查询出每个会话里涉及到的好友是谁
            messageSession.setSessionId(sessionId);
            List<FriendInfo> friendInfos = messageSessionService.getFriendsBySessionId(sessionId, userInfo.getUserId());
            //遍历sessionId，查询出每个会话的最后一条消息
            //    有可能出现按照会话 id 查不到消息的情况 (新创建的会话可能还没来得及发消息呢
            System.out.println(friendInfos.toString());
            messageSession.setFriends(friendInfos);
            String lastMessage = messageService.getListMessageBySessionId(sessionId);
            if (lastMessage == null) {
                messageSession.setLastMessage("");
            } else {
                messageSession.setLastMessage(lastMessage);

            }
            messageSessionList.add(messageSession);
        }
        //最终目标构造出MessageSession对象的数组
        return Result.success(messageSessionList);
    }

    //另一种获取session对像的方式
    @RequestMapping("/session")
    @Transactional
    public Result addMessageSession(Integer toUserId, @SessionAttribute("userInfo") UserInfo userInfo) {
        System.out.println(toUserId);
        HashMap<String, Integer> response = new HashMap<>();
        //进行数据库进行插入操作
        // 先给MessageSession中插入记录 使用这个参数的目的是为了获取到会话中的SessionId
        //换而言之 MessageSession 中的List<friendInfo> 和 lastMessage 都有用不上
        MessageSession messageSession = new MessageSession();
        messageSessionService.addMessageSession(messageSession);
        //给messageSessionUser表进行插入
        MessageSessionUserItem item1 = new MessageSessionUserItem();
        item1.setSessionId(messageSession.getSessionId());
        item1.setUserId(userInfo.getUserId());
        MessageSessionUserItem item2 = new MessageSessionUserItem();
        item2.setSessionId(messageSession.getSessionId());
        item2.setUserId(toUserId);
        messageSessionService.addMessageSessionUser(item1);
        messageSessionService.addMessageSessionUser(item2);
        log.info("addMessageSession 新增会话成功！ sessionId:" + messageSession.getSessionId() + "userId1:" + userInfo.getUserId()
                + "userId2:" + toUserId);
        response.put("sessionId", messageSession.getSessionId());
        //返回对象是普通对象也可以返回的是map也可以
        return Result.success(response);
    }
}
